#!/usr/bin/env python
# -*- coding:utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Integer, String, Unicode, UnicodeText, DateTime
from sqlalchemy.sql.sqltypes import TIMESTAMP
from sqlalchemy.sql import func
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

''' user_detail collection has
    id:             自增id（int）
    userid:         用户id（int）
    sex:            用户性别（string）
    sexot:          用户性取向（string）
    love:           用户情感状态（string）
    horo:           用户星座（string）
    utime:          用户资料最后更新时间（datetime）
'''

class UserDetailItem(object):

    def to_dict(self):
        res = {}
        res['userid'] = self.userid
        res['sex'] = self.sex
        res['sexot'] = self.sexot
        res['love'] = self.love
        res['horo'] = self.horo
        res['utime'] = self.utime.strftime("%Y-%m-%d %H:%M:%S")\
            if self.utime else ""

        return res

    def __repr__(self):
        return "%d" % (self.userid)


user_detail_table = Table(
    'user_detail', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('userid', Integer, index=True, nullable=False),
    Column('sex', Unicode(65), nullable=True),
    Column('sexot', Unicode(65), nullable=True),
    Column('love', Unicode(65), nullable=True),
    Column('horo', Unicode(65), nullable=True),
    Column('utime', TIMESTAMP, server_default=func.now(), onupdate=func.now())
)

mapper(UserDetailItem, user_detail_table)

def create_user_detail_table_if_not_exist():
    metadata.create_all(engine)

def add_user_detail_item(p_item):
    item = UserDetailItem()
    item.userid = p_item['userid']
    item.sex = p_item['sex']
    item.sexot = p_item['sexot']
    item.love = p_item['love']
    item.horo = p_item['horo']

    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

def get_user_detail_by_userid(p_userid):
    try:
        session = Session()
        user_detail = session.query(UserDetailItem).filter_by(userid=p_userid).first()
        if user_detail:
            return user_detail.to_dict()
        return None
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def update_user_detail_by_userid(p_userid, p_sex, p_sexot, p_love, p_horo):
    try:
        sex = p_sex
        sexot = p_sexot
        love = p_love
        horo = p_horo
        session = Session()
        item = session.query(UserDetailItem).filter_by(userid=p_userid).first()
        if item is None:
            detail_item = {
                'userid':   p_userid,
                'sex':      p_sex,
                'sexot':    p_sexot,
                'love':     p_love,
                'horo':     p_horo,
            }
            add_user_detail_item(detail_item)
        else:
            if sex:
                session.query(UserDetailItem).filter_by(userid=p_userid).update({"sex": sex})
            if sexot:
                session.query(UserDetailItem).filter_by(userid=p_userid).update({"sexot": sexot})
            if love:
                session.query(UserDetailItem).filter_by(userid=p_userid).update({"love": love})
            if horo:
                session.query(UserDetailItem).filter_by(userid=p_userid).update({"horo": horo})
            session.flush()
            session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def update_fake_user_detail_by_userid(p_userid, p_item):
    try:
        session = Session()
        session.query(UserDetailItem).filter_by(userid=p_userid).update(p_item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

if __name__ == "__main__":
    create_user_detail_table_if_not_exist()